package com.qianfeng.android.baoman;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.android.baoman.adapter.CinemaListAdapter;
import com.qianfeng.android.baoman.model.Cinema;
import com.qianfeng.android.baoman.model.CinemaSubItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;


public class CinemaListActivity extends BaseActivity implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private List<CinemaSubItem> cinemaSubItemList;
    private CinemaListAdapter adapter;
    private LinearLayout load_layout;
    private PullToRefreshListView refreshListView;
    private ImageView image_error;

    private int pageCount;
    private int cinemaId;
    //代表是否到最底部
    private boolean isBottom = false;
    private ListView listView;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cinema_list);
        setBackVisible(true);
        //加载数据时显示
        load_layout = (LinearLayout) findViewById(R.id.load_layout);

        image_error = (ImageView) findViewById(R.id.cinemaList_image_error);
        image_error.setOnClickListener(this);
        //设置标题
        Intent intent = getIntent();
        if (intent != null) {
            Cinema cinema = (Cinema) intent.getSerializableExtra("cinema");
            if (cinema != null) {
                setActionBarTitle(cinema.getName());
            }
            refreshListView = (PullToRefreshListView) findViewById(R.id.cinemaList_pullRoRefreshList);
            refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            listView = refreshListView.getRefreshableView();

            cinemaSubItemList = new LinkedList<>();
            adapter = new CinemaListAdapter(this, cinemaSubItemList);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(this);

            Drawable drawable = getResources().getDrawable(R.drawable.arrow_down);
            refreshListView.setLoadingDrawable(drawable);
            // 设置加载中的标题
            refreshListView.setRefreshingLabel("加载...");
            // 设置“松开”提醒
            refreshListView.setReleaseLabel("松开可以刷新");
            refreshListView.setOnRefreshListener(this);

            pageCount = 1;
            cinemaId = cinema.getId();
            loadData(Constants.getMovieSubList(null, cinemaId, pageCount));
        }
    }

    private void loadData(String url) {
        load_layout.setVisibility(View.VISIBLE);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET,
                url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        String result = objectResponseInfo.result;
                        try {
                            refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
                            refreshListView.onRefreshComplete();
                            JSONObject object = new JSONObject(result);
                            int total_pages = object.getInt("total_pages");
                            if (pageCount > total_pages) {
                                Toast.makeText(CinemaListActivity.this, "已到底部", Toast.LENGTH_SHORT).show();
                                isBottom = true;
                                load_layout.setVisibility(View.GONE);
                                image_error.setVisibility(View.GONE);
                                return;
                            }
                            JSONArray articles = object.getJSONArray("articles");
                            for (int i = 0; i < articles.length(); i++) {
                                JSONObject jsonObject = articles.getJSONObject(i);
                                CinemaSubItem cinemaSubItem = new CinemaSubItem();
                                cinemaSubItem.parseJSON(jsonObject);
                                if (!cinemaSubItemList.contains(cinemaSubItem)) {
                                    cinemaSubItemList.add(cinemaSubItem);
                                }
                            }
                            adapter.notifyDataSetChanged();
                            load_layout.setVisibility(View.GONE);
                            image_error.setVisibility(View.GONE);
                            Log.i("CinemaListActivity", cinemaSubItemList.size() + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        Toast.makeText(CinemaListActivity.this, "网络问题", Toast.LENGTH_SHORT).show();
                        image_error.setVisibility(View.VISIBLE);
                        refreshListView.setVisibility(View.GONE);
                        load_layout.setVisibility(View.GONE);
                        pageCount = 1;
                        refreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
                    }
                });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //跳转到评论界面
        CinemaSubItem cinemaSubItem = cinemaSubItemList.get(position - listView.getHeaderViewsCount());
        Intent intent = new Intent(this, CinemaCommentActivity.class);
        intent.putExtra("cinemaSubItem", cinemaSubItem);
        startActivity(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                String url = Constants.getMovieSubList(null, cinemaId, 1);
//                pageCount = 1;
                loadData(url);
                refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }, 1000);

    }


    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pageCount++;
                String url = Constants.getMovieSubList(null, cinemaId, pageCount);
                loadData(url);

            }
        }, 1000);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        switch (id) {
            case R.id.cinemaList_image_error:
                image_error.setVisibility(View.GONE);
                loadData(Constants.MOVIE_INDEX_URL);
                break;
        }
    }
}
